const loginContainer = document.getElementById("login-container");
const loginLink = document.getElementById("login-link");

loginLink.addEventListener("click", function(event){
    event.preventDefault();
    loginContainer.classList.remove("hidden");
    registerContainer.classList.add("hidden");
});

const loginForm = document.getElementById("login-form");

loginForm.addEventListener("submit", function(event) {
    event.preventDefault();
    const formData = new FormData(event.target);
    const username = formData.get("username");
    const password = formData.get("password");
    // 判断每个字段是否为空
    if (!username) {
        alert("用户名为空！");
        return;
    }
    if (!password) {
        alert("密码为空！");
        return;
    }
    // 发送登录请求
    // fetch('https://localhost:8080/api/user/login', {
    fetch('https://api.fzuenactus.org.cn/api/user/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: password
        }),
        mode: 'cors',
        credentials: 'include'
    })
    .then(response => {
        if (response.ok) {
            //登录成功
            console.log(response);
            response.json().then(data=>{
                localStorage.setItem('token', data.token);
                localStorage.setItem('user', JSON.stringify(data.user));
                alert(data.message);// 显示登录成功信息
                window.location.href = 'competitions_management.html';
                // window.location.href = 'chromatic-speaker.html';
            });
        } else {
            //登录失败
            console.log(response);
            response.json().then(error=>{
                alert(error.message);// 显示其他错误信息，例如用户名不存在、密码错误等
            });
        }
    })
    .catch(error => {
        console.error(error);
    });
});